/** @format */

const to = (promise: Promise<unknown>): Promise<unknown> => {
  return promise.then((data: any) => [null, data]).catch((err: any) => [err]);
};

// YYYY 代表年，MM 月，DD 日，HH 时，mm 分 SS 秒，格式可以自由组合
// formate(Date.now(), 'YYYY/MM/DD HH:mm') // 2019/1/7 22:43
// formate(Date.now(), 'MM-DD-YYYY HH:mm:SS') // 1-7-2019 22:43:13
const formateTime = (timeString: string | number, formateStr: string): string => {
  const time: any = new Date(timeString);
  const tempTime: any = {
    year: time.getFullYear(),
    month: time.getMonth() + 1 < 10 ? `0${time.getMonth() + 1}` : time.getMonth() + 1,
    date: time.getDate() < 10 ? `0${time.getDate()}` : time.getDate(),
    hours: time.getHours() < 10 ? `0${time.getHours()}` : time.getHours(),
    minutes: time.getMinutes() < 10 ? `0${time.getMinutes()}` : time.getMinutes(),
    seconds: time.getSeconds() < 10 ? `0${time.getSeconds()}` : time.getSeconds(),
  };

  const tempKey: Array<{val: string; key: string}> = [
    {val: 'YYYY', key: 'year'},
    {val: 'MM', key: 'month'},
    {val: 'DD', key: 'date'},
    {val: 'HH', key: 'hours'},
    {val: 'mm', key: 'minutes'},
    {val: 'SS', key: 'seconds'},
  ];

  tempKey.forEach((key: any) => {
    if (formateStr.indexOf(key.val) > -1) {
      formateStr = formateStr.replace(key.val, tempTime[key.key]);
    }
  });

  return formateStr;
};

export {to, formateTime};
